﻿using System;
using System.Xml;
using System.Management;

namespace NetTask5
{
    internal class DeviceHeader
    {
        public string Name { get; set; }
        public string Query { get; set; }
        public string[] Bloks { get; set; }
    }

    class Hardware
    {
        private XmlWriter _xmlWriter;

        public Hardware()
        {
            _xmlWriter = null;
        }

        public void GetDeviceInfo(DeviceHeader dh)
        {
            try
            {
                _xmlWriter.WriteStartElement(dh.Name);
                var searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM " + dh.Query);

                foreach (ManagementObject queryObj in searcher.Get())
                {
                    _xmlWriter.WriteStartElement("Devise");
                    foreach (var item in dh.Bloks)
                    {
                        _xmlWriter.WriteStartElement(item);
                        if ((
                               (dh.Query == "Win32_DiskDrive" && item == "Size")
                            || (dh.Query == "Win32_PhysicalMemory" && item == "Capacity"))
                            && queryObj[item] != null)
                            _xmlWriter.WriteString((long.Parse(queryObj[item].ToString()) / 1048576).ToString());
                        else _xmlWriter.WriteString(queryObj[item] == null ? "NULL" : queryObj[item].ToString());
                        _xmlWriter.WriteEndElement();
                    }
                    _xmlWriter.WriteEndElement();
                }
                _xmlWriter.WriteEndElement();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public void GetHardWareInfo(DeviceHeader[] devices, string xmlPath, string xlsPath)
        {
            var settings = new XmlWriterSettings {Indent = true, IndentChars = "    "};

            using (_xmlWriter = XmlWriter.Create(xmlPath, settings))
            {
                _xmlWriter.WriteStartDocument();
                _xmlWriter.WriteProcessingInstruction("xml-stylesheet", @"type=""text/xsl"" href="""+xlsPath+"\"");

                _xmlWriter.WriteStartElement("Devises");

                foreach (var dh in devices) GetDeviceInfo(dh);

                _xmlWriter.WriteEndElement();
            }

            _xmlWriter = null;
        }
    }
}